package com.fastCms.business.frame.aspects;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.handlers.StrictFill;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * 默认参数入库处理
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        // 处理创建时间更新时间
        Date now = new Date();
        this.strictInsertFill(metaObject, CREATE_TIME, Date.class, now);
        this.strictInsertFill(metaObject, UPDATE_TIME, Date.class, now);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 处理更新时间和更新人
        this.strictUpdateFill(metaObject, UPDATE_TIME, Date.class, new Date());
    }

    @Override
    public MetaObjectHandler strictFill(boolean insertFill, TableInfo tableInfo, MetaObject metaObject,
                                        List<StrictFill<?, ?>> strictFills) {
        if ((insertFill && tableInfo.isWithInsertFill()) || (!insertFill && tableInfo.isWithUpdateFill())) {
            strictFills.forEach(i -> {
                final String fieldName = i.getFieldName();
                final Class<?> fieldType = i.getFieldType();
                // insert时有值不覆盖 update时有值也强行覆盖
                if (insertFill) {
                    tableInfo.getFieldList().stream()
                        .filter(j -> j.getProperty().equals(fieldName) && fieldType.equals(j.getPropertyType())
                            && ((insertFill && j.isWithInsertFill()) || (!insertFill && j.isWithUpdateFill())))
                        .findFirst().ifPresent(j -> strictFillStrategy(metaObject, fieldName, i.getFieldVal()));
                } else {
                    tableInfo.getFieldList().stream()
                        .filter(j -> j.getProperty().equals(fieldName) && fieldType.equals(j.getPropertyType())
                            && ((insertFill && j.isWithInsertFill()) || (!insertFill && j.isWithUpdateFill())))
                        .findFirst().ifPresent(j -> forceFillStrategy(metaObject, fieldName, i.getFieldVal()));
                }
            });
        }
        return this;
    }

    /**
     * 如果属性有值也覆盖 如果填充值为null则不填充
     *
     * @param metaObject
     * @param fieldName
     * @param fieldVal
     * @return
     */
    public MetaObjectHandler forceFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        Object obj = fieldVal.get();
        if (Objects.nonNull(obj)) {
            metaObject.setValue(fieldName, obj);
        }
        return this;
    }
}
